import  ftplib
import os.path
import re
import datetime

import gzip


FTPHost=''
user=''
password=''
LOCALHost=''



class HandleFile():

    def __init__(self,Filepath=os.path.dirname(__file__)):

        self.today=datetime.date.today()
        self.yesterday=self.today-datetime.timedelta(days=1)

        self.AllFilelist=os.listdir(Filepath)
        self.LogFile=re.compile(r'.*old$')
        self.yesterdaylog = re.compile(r'.*%s.*old$' % self.yesterday.strftime("%Y%m%d"))
        self.todaylog = re.compile(r'.*%s.*old$' % self.today.strftime("%Y%m%d"))
        self.LastFile= re.compile(r'.*gz$')

        self.FileName='unw-'+LOCALHost+'-'+str(self.today.strftime("%Y%m%d"))

        self.Filelist=[]
    def run(self):

        try:
            self.Searchile()
        except Exception as SeachFileError:
            print(SeachFileError)

        try:
            self.RemoveFile()
        except Exception as RemoveFileError:
           print("RemoveFileError:%s " % str(RemoveFileError))


        try:
            self.MargeFile()
        except Exception as  MargeFileError:
            print("MargeFileError:%s " % MargeFileError)



        try:
            self.CommpressedFile()
        except Exception as CommpressFileError:
            print("CommpressFileError:%s " % CommpressFileError)


    def Searchile(self):
        for file in self.AllFilelist:
            if self.LogFile.search(file) or self.LastFile.search(file):
                self.Filelist.append(file)


    def MargeFile(self):
        with open(self.FileName,'a+') as OUTFile:
            for file in self.Filelist:
                print(file)
                with open(file,'r') as file:
                    OUTFile.write(file.read()+"\n")



    def CommpressedFile(self):
        with open(self.FileName, 'rb') as OUTFile:
            self.outfilename=self.FileName+".gz"
            with gzip.GzipFile(filename="", mode="wb", compresslevel=9, fileobj=open(str(self.outfilename), 'wb')) as g :
                g.write(OUTFile.read())
        os.remove(self.FileName)
    def RemoveFile(self):
        for lastfile in self.Filelist:
            if not  self.yesterdaylog.search(lastfile):
                if  self.todaylog.search(lastfile) :
                     self.Filelist.remove(lastfile)
                else:
                    self.Filelist.remove(lastfile)
                    os.remove(lastfile)

class FTPClient(object):

    def FtpConnect(self,host, username, password):
        self.ftp = ftplib.FTP()
        self.ftp.connect(host, 21)
        self.ftp.login(username, password)
        print(self.ftp.getwelcome())
        return self.ftp

    def UpLoadFile(self, localpath, remotepath="/home/ftp/htcache/"):
        bufsize = 4096
        fp = open(localpath, 'rb')
        self.ftp.storbinary('STOR %s' % remotepath, fp, bufsize)
        self.ftp.set_debuglevel(0)
        self.ftp.close()
        print('uploadlog success~!!')






if __name__ == "__main__":
    h=HandleFile()
    h.run()
    LocalFile=str(os.path.dirname(__file__))+"/"+h.outfilename
    RemoteFile=str("/home/ftp/htcache/"+h.outfilename)
    print("LOCALFILE: %s"%LocalFile)
    print('REMOTEFILE: %s'%RemoteFile)
    try:
        myftp=FTPClient()
        myftp.FtpConnect(FTPHost,user,password)
        myftp.UpLoadFile(LocalFile,RemoteFile)
    except Exception as FTPConnectError:
        print(FTPConnectError)
        exit()
